package cn.mujiankeji.mbrowser.数据.数据库

import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow

/**
 * UA标识数据表
 * 用于存储用户代理(User Agent)配置
 */
@Entity(tableName = "UserAgent")
data class DBUa(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    var id: Long = 0,

    @ColumnInfo(name = "name")
    var 名称: String = "",

    @ColumnInfo(name = "user_agent")
    var UA: String = "",

    @ColumnInfo(name = "remark")
    var 备注: String = "",

    @ColumnInfo(name = "update_time")
    var 更新时间: Long = System.currentTimeMillis(),

    @ColumnInfo(name = "is_default")
    var 默认: Boolean = false,
)

/**
 * UA标识数据访问对象
 */
@Dao
interface DaoUa {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun 添加UA(ua: DBUa): Long

    @Update
    suspend fun 更新UA(ua: DBUa)

    @Delete
    suspend fun 删除UA(ua: DBUa)

    @Query("SELECT * FROM UserAgent ORDER BY update_time DESC")
    fun 获取所有UA(): Flow<List<DBUa>>

    @Query("SELECT * FROM UserAgent WHERE id = :id")
    suspend fun 按ID获取UA(id: Long): DBUa?

    @Query("SELECT * FROM UserAgent WHERE is_default = 1 LIMIT 1")
    suspend fun 获取默认UA(): DBUa?

    @Query("SELECT * FROM UserAgent WHERE is_default = 1 LIMIT 1")
    fun 获取默认UAFlow(): Flow<DBUa?>

    @Query("UPDATE UserAgent SET is_default = 0 WHERE is_default = 1")
    suspend fun 清除所有默认标记()

    @Query("UPDATE UserAgent SET is_default = 1 WHERE id = :id")
    suspend fun 设置为默认(id: Long)

    /**
     * 设置指定UA为默认，并清除其他UA的默认标记
     */
    suspend fun 设置默认UA(id: Long) {
        清除所有默认标记()
        设置为默认(id)
    }
}